package com.haoxin.ai_course.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.commons.lang.StringUtils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class RemoteShellTool {
	private Connection conn;
	private String ipAddr;
	private String charset = Charset.defaultCharset().toString();
	private String userName;
	private String password;
	
	public RemoteShellTool(String ipAddr, String userName, String password,
			String charset) {
		this.ipAddr = ipAddr;
		this.userName = userName;
		this.password = password;
		if (charset != null) {
			this.charset = charset;
		}
	}
   /**
     * 
     * @Title: login  
     * @Description: 用户名密码方式  远程登录linux服务器
     * @return: Boolean     
     * @throws
     */
	public boolean login(){
		boolean flag = false;
		try {
			conn = new Connection(ipAddr);
			conn.connect(); // 连接
			flag = conn.authenticateWithPassword(userName, password); // 认证
			if (flag) {
				System.out.println("=========登陆xxx服务器的用户名和密码认证成功！");
			} else {
				System.out.println("=========登陆xxx服务器的用户名和密码认证失败！");;
				conn.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}
   /**
    * 
    * @Title: processStdout
    * @Description: 解析脚本执行的返回结果
    * @param in 输入流对象
    * @param charset 编码
    * @return String 以纯文本的格式返回
    * @throws
     */
	public String processStdout(InputStream in, String charset) {
		InputStream stdout = new StreamGobbler(in);
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line + "\n");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	/** 
     * @author Ickes 
     * 远程执行shll脚本或者命令 
     * @param cmd 
     *      即将执行的命令 
     * @return 
     *      命令执行完后返回的结果值,如果命令执行失败，返回空字符串，不是null
     * @since V0.1 
     */  
	public String exec(String cmds) {
		String result = "";
		try {
			if (this.login()) {
				Session session = conn.openSession(); // 打开一个会话
				session.execCommand(cmds);
				result = this.processStdout(session.getStdout(), this.charset);
				if(StringUtils.isBlank(result)){// 如果为得到标准输出为空字符串，说明脚本执行出错了
					result = processStdout(session.getStderr(),this.charset);
					System.out.println("-----脚本执行出错了，返回空空字符串-----:"+result);
				}
				session.close();
				conn.close();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return result;
	}


}

